package com.hzw.saas.web.shell.listener;

import com.hzw.saas.web.shell.event.ShellEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @author sonam
 * @since 2021/5/29 11:24
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ShellListener {

    @Resource
    private SimpUserRegistry userRegistry; // 所有用户连接信息

    private final SimpMessagingTemplate messagingTemplate;

    @EventListener(ShellEvent.class)
    public void sendMsgToShell(ShellEvent shellEvent) {
        String msg = shellEvent.getMsg();
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        log.trace("send msg: {},length: {}", msg, bytes.length);
        messagingTemplate.convertAndSendToUser(shellEvent.getUserName(), shellEvent.getPath(), msg);
    }

}
